// import 'package:firebase_ui_auth/firebase_ui_auth.dart';
import 'package:flutter/material.dart';
import 'package:insail_flutter_boot_template/feature/home/presentation/screens/home_screen.dart';
import 'package:insail_flutter_boot_template/feature/profile/presentation/screens/about_us_screen.dart';
import 'package:insail_flutter_boot_template/feature/profile/presentation/screens/settings_screen.dart';
import 'package:insail_flutter_boot_template/feature/profile/presentation/screens/theme_screen.dart';
import '../feature/auth/data/providers/auth_provider.dart';
import 'package:riverpod/riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:go_router/go_router.dart';

import '../feature/auth/presentation/screens/custom_login_screen.dart';
import '../feature/auth/presentation/screens/custom_register_screen.dart';
import '../feature/profile/presentation/custom_profile_screen.dart';
import '../feature/onboarding/data/onboarding_repository.dart';
import '../feature/onboarding/presentation/onboarding_screen.dart';
import '../feature/profile/presentation/screens/profile_screen.dart';
import 'go_router_refresh_stream.dart';
import 'not_found_screen.dart';
import 'scaffold_with_nested_navigation.dart';

part 'app_router.g.dart';

// private navigators
final _rootNavigatorKey = GlobalKey<NavigatorState>();
final _homeNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'home');
final _entriesNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'entries');
final _accountNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'account');

enum AppRoute {
  onboarding,
  signIn,
  register,
  home,
  job,
  addJob,
  editJob,
  entry,
  addEntry,
  editEntry,
  entries,
  profile,
  aboutUs,
  settings,
  theme,
  notFound,
}

@riverpod
GoRouter goRouter(Ref ref) {
  final authRepository = ref.watch(authAppProviderProvider); // 使用自定义登录

  return GoRouter(
    initialLocation: '/signIn',
    navigatorKey: _rootNavigatorKey,
    debugLogDiagnostics: true,
    redirect: (context, state) {
      final onboardingRepository =
          ref.read(onboardingRepositoryProvider).requireValue;
      final didCompleteOnboarding = onboardingRepository.isOnboardingComplete();
      final path = state.uri.path;

      // 如果用户没有完成入门引导（onboarding），则重定向到入门页面
      if (!didCompleteOnboarding) {
        // Always check state.subloc before returning a non-null route
        // https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/redirection.dart#L78
        if (path != '/onboarding') {
          return '/onboarding';
        }
        return null;
      }
      final isLoggedIn = authRepository.currentUser != null;
      if (isLoggedIn) {
        // 检查path是否以指定的前缀开始
        if (path.startsWith('/onboarding') || path.startsWith('/signIn')) {
          return '/home';
        }
      } else {
        if (path.startsWith('/onboarding') ||
            path.startsWith('/home') ||
            path.startsWith('/account')) {
          return '/signIn';
        }
      }
      return null;
    },
    refreshListenable: GoRouterRefreshStream(authRepository.authStateChanges()),
    routes: [
      // AppRoute.onboarding 是一个枚举值，而 .name 是 Dart 语言中，获取枚举值名称的方式。
      GoRoute(
        path: '/onboarding',
        name: AppRoute.onboarding.name,
        pageBuilder: (context, state) => const NoTransitionPage(
          child: OnboardingScreen(),
        ),
      ),
      GoRoute(
        path: '/signIn',
        name: AppRoute.signIn.name,
        pageBuilder: (context, state) => const NoTransitionPage(
          child: CustomLoginScreen(),
        ),
      ),
      GoRoute(
        path: '/register',
        name: AppRoute.register.name,
        pageBuilder: (context, state) => const NoTransitionPage(
          child: CustomRegisterScreen(),
        ),
      ),
      // 使用 StatefulShellRoute 来管理嵌套导航结构（如底部导航栏或侧边栏）。这种方式支持状态保持，允许在不同的导航分支之间切换时保留页面状态。
      // https://github.com/flutter/packages/blob/main/packages/go_router/example/lib/stateful_shell_route.dart
      StatefulShellRoute.indexedStack(
        pageBuilder: (context, state, navigationShell) => NoTransitionPage(
          child: ScaffoldWithNestedNavigation(navigationShell: navigationShell),
        ),
        branches: [
          StatefulShellBranch(
            navigatorKey: _homeNavigatorKey,
            routes: [
              GoRoute(
                path: '/home',
                name: AppRoute.home.name,
                pageBuilder: (context, state) => const NoTransitionPage(
                  child: HomeScreen(),
                ),
                routes: [
                  GoRoute(
                    path: 'add',
                    name: AppRoute.addJob.name,
                    parentNavigatorKey: _rootNavigatorKey,
                    pageBuilder: (context, state) {
                      return const MaterialPage(
                        fullscreenDialog: true,
                        child: CustomProfileScreen(),
                      );
                    },
                  ),
                  // GoRoute(
                  //   path: ':id',
                  //   name: AppRoute.job.name,
                  //   pageBuilder: (context, state) {
                  //     final id = state.pathParameters['id']!;
                  //     return MaterialPage(
                  //       child: JobEntriesScreen(jobId: id),
                  //     );
                  //   },
                  //   routes: [
                  //     GoRoute(
                  //       path: 'entries/add',
                  //       name: AppRoute.addEntry.name,
                  //       parentNavigatorKey: _rootNavigatorKey,
                  //       pageBuilder: (context, state) {
                  //         final jobId = state.pathParameters['id']!;
                  //         return MaterialPage(
                  //           fullscreenDialog: true,
                  //           child: EntryScreen(
                  //             jobId: jobId,
                  //           ),
                  //         );
                  //       },
                  //     ),
                  //     GoRoute(
                  //       path: 'entries/:eid',
                  //       name: AppRoute.entry.name,
                  //       pageBuilder: (context, state) {
                  //         final jobId = state.pathParameters['id']!;
                  //         final entryId = state.pathParameters['eid']!;
                  //         final entry = state.extra as Entry?;
                  //         return MaterialPage(
                  //           child: EntryScreen(
                  //             jobId: jobId,
                  //             entryId: entryId,
                  //             entry: entry,
                  //           ),
                  //         );
                  //       },
                  //     ),
                  //     GoRoute(
                  //       path: 'edit',
                  //       name: AppRoute.editJob.name,
                  //       pageBuilder: (context, state) {
                  //         final jobId = state.pathParameters['id'];
                  //         final job = state.extra as Job?;
                  //         return MaterialPage(
                  //           fullscreenDialog: true,
                  //           child: EditJobScreen(jobId: jobId, job: job),
                  //         );
                  //       },
                  //     ),
                  //   ],
                  // ),
                ],
              ),
            ],
          ),
          StatefulShellBranch(
            navigatorKey: _entriesNavigatorKey,
            routes: [
              GoRoute(
                path: '/entries',
                name: AppRoute.entries.name,
                pageBuilder: (context, state) => const NoTransitionPage(
                  child: CustomProfileScreen(),
                ),
              ),
            ],
          ),
          StatefulShellBranch(
            navigatorKey: _accountNavigatorKey,
            routes: [
              GoRoute(
                  path: '/account',
                  name: AppRoute.profile.name,
                  pageBuilder: (context, state) => const NoTransitionPage(
                        child: ProfileScreen(),
                      ),
                  routes: [
                    GoRoute(
                      path: '/aboutUs',
                      name: AppRoute.aboutUs.name,
                      parentNavigatorKey: _rootNavigatorKey,
                      pageBuilder: (context, state) {
                        return const NoTransitionPage(
                          child: AboutUsScreen(),
                        );
                      },
                    ),
                    GoRoute(
                      path: '/settings',
                      name: AppRoute.settings.name,
                      parentNavigatorKey: _rootNavigatorKey,
                      pageBuilder: (context, state) {
                        return const NoTransitionPage(
                          child: SettingsScreen(),
                        );
                      },
                    ),
                    GoRoute(
                      path: '/theme',
                      name: AppRoute.theme.name,
                      parentNavigatorKey: _rootNavigatorKey,
                      pageBuilder: (context, state) {
                        return const NoTransitionPage(
                          child: ThemeSettingScreen(),
                        );
                      },
                    ),
                  ]),
            ],
          ),
        ],
      ),
    ],
    errorPageBuilder: (context, state) => const NoTransitionPage(
      child: NotFoundScreen(),
    ),
  );
}
